<script setup>
import { ref, computed, onMounted } from 'vue'
import { useCategoryStore } from '../../stores/categoryStore'

const props = defineProps({
  task: {
    type: Object,
    default: () => ({
      title: '',
      description: '',
      completed: false,
      dueDate: null,
      reminder: null,
      priority: 'medium',
      categoryId: null,
    })
  },
  isEditing: {
    type: Boolean,
    default: false
  }
})

const emit = defineEmits(['save', 'cancel'])

// 任务表单数据
const taskForm = ref({
  title: props.task.title,
  description: props.task.description || '',
  completed: props.task.completed || false,
  dueDate: props.task.dueDate ? formatDateForInput(new Date(props.task.dueDate)) : '',
  reminder: props.task.reminder ? formatTimeForInput(new Date(props.task.reminder)) : '',
  priority: props.task.priority || 'medium',
  categoryId: props.task.categoryId || null,
})

// 格式化日期为YYYY-MM-DD格式（input[type="date"]需要的格式）
function formatDateForInput(date) {
  const year = date.getFullYear()
  const month = String(date.getMonth() + 1).padStart(2, '0')
  const day = String(date.getDate()).padStart(2, '0')
  return `${year}-${month}-${day}`
}

// 格式化时间为HH:MM格式（input[type="time"]需要的格式）
function formatTimeForInput(date) {
  const hours = String(date.getHours()).padStart(2, '0')
  const minutes = String(date.getMinutes()).padStart(2, '0')
  return `${hours}:${minutes}`
}

// 表单验证规则
const rules = {
  title: [v => !!v || '请输入任务标题'],
  categoryId: [v => !!v || '请选择分类']
}

// 从Store获取分类
const categoryStore = useCategoryStore()
const categories = computed(() => categoryStore.sortedCategories)

// 获取分类的颜色
const getCategoryColor = computed(() => {
  if (!taskForm.value.categoryId) return 'primary'
  const category = categories.value.find(c => c.id === taskForm.value.categoryId)
  return category ? category.color : 'primary'
})

// 优先级选项
const priorityOptions = [
  { value: 'low', text: '低', icon: 'mdi-flag', color: 'success' },
  { value: 'medium', text: '中', icon: 'mdi-flag', color: 'warning' },
  { value: 'high', text: '高', icon: 'mdi-flag', color: 'error' }
]

// 在组件挂载时，如果没有分类，则初始化默认分类
onMounted(async () => {
  if (categories.value.length === 0) {
    await categoryStore.loadCategories()
    if (categories.value.length > 0 && !taskForm.value.categoryId) {
      taskForm.value.categoryId = categories.value[0].id
    }
  }
})

// 保存任务
const saveTask = () => {
  // 基本验证
  if (!taskForm.value.title.trim()) {
    return
  }
  
  // 准备提交的数据
  const taskData = {
    title: taskForm.value.title.trim(),
    description: taskForm.value.description.trim(),
    completed: taskForm.value.completed,
    dueDate: taskForm.value.dueDate ? new Date(taskForm.value.dueDate) : null,
    reminder: taskForm.value.reminder ? new Date(`2000-01-01T${taskForm.value.reminder}`) : null,
    priority: taskForm.value.priority,
    categoryId: taskForm.value.categoryId,
  }
  
  emit('save', taskData)
}

// 取消
const cancel = () => {
  emit('cancel')
}

// 判断是否是编辑模式
const formTitle = computed(() => {
  return props.isEditing ? '编辑任务' : '添加任务'
})
</script>

<template>
  <v-card class="task-form">
    <v-card-title>{{ formTitle }}</v-card-title>
    
    <v-card-text>
      <v-form @submit.prevent="saveTask">
        <!-- 任务标题 -->
        <v-text-field
          v-model="taskForm.title"
          label="任务标题"
          :rules="rules.title"
          required
          class="mb-2"
          hide-details="auto"
        ></v-text-field>
        
        <!-- 任务描述 -->
        <v-textarea
          v-model="taskForm.description"
          label="描述（可选）"
          rows="2"
          auto-grow
          class="mb-2"
          hide-details
        ></v-textarea>
        
        <!-- 分类选择 -->
        <v-select
          v-model="taskForm.categoryId"
          :items="categories"
          item-title="name"
          item-value="id"
          label="分类"
          :rules="rules.categoryId"
          required
          class="mb-2"
          hide-details="auto"
        >
          <template v-slot:selection="{ item }">
            <v-chip
              :color="item.raw.color"
              label
              size="small"
              class="mr-1"
            >
              <v-icon
                start
                :icon="item.raw.icon"
                size="small"
              ></v-icon>
              {{ item.raw.name }}
            </v-chip>
          </template>
          
          <template v-slot:item="{ item, props: slotProps }">
            <v-list-item
              v-bind="slotProps"
              :title="item.raw.name"
            >
              <template v-slot:prepend>
                <v-icon :color="item.raw.color">{{ item.raw.icon }}</v-icon>
              </template>
            </v-list-item>
          </template>
        </v-select>
        
        <!-- 优先级选择 -->
        <v-radio-group
          v-model="taskForm.priority"
          label="优先级"
          inline
          hide-details
          class="mb-2"
        >
          <v-radio
            v-for="option in priorityOptions"
            :key="option.value"
            :value="option.value"
            :label="option.text"
            :color="option.color"
          >
            <template v-slot:label>
              <div class="d-flex align-center">
                <v-icon :color="option.color" size="small" class="mr-1">{{ option.icon }}</v-icon>
                {{ option.text }}
              </div>
            </template>
          </v-radio>
        </v-radio-group>
        
        <!-- 日期选择 -->
        <v-text-field
          v-model="taskForm.dueDate"
          label="截止日期"
          type="date"
          class="mb-2"
          prepend-icon="mdi-calendar"
          clearable
          hide-details
          :color="getCategoryColor"
        ></v-text-field>
        
        <!-- 时间选择 -->
        <v-text-field
          v-model="taskForm.reminder"
          label="提醒时间"
          type="time"
          class="mb-2"
          prepend-icon="mdi-clock-outline"
          clearable
          hide-details
          :color="getCategoryColor"
        ></v-text-field>
      </v-form>
    </v-card-text>
    
    <v-card-actions>
      <v-spacer></v-spacer>
      <v-btn variant="text" @click="cancel">取消</v-btn>
      <v-btn 
        color="primary" 
        variant="elevated" 
        @click="saveTask"
        :disabled="!taskForm.title.trim() || !taskForm.categoryId"
      >
        保存
      </v-btn>
    </v-card-actions>
  </v-card>
</template>

<style scoped>
.task-form {
  max-width: 600px;
  margin: 0 auto;
}
</style> 